<script setup>
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue'
import { ref ,onBeforeMount, reactive, toRefs, computed} from 'vue';
import { da } from 'element-plus/es/locales.mjs';
import { listHandler } from '../../api/generic.js';
import { deleteTableRow } from '../../utils/utils';
import Table from '../components/Table.vue';
import { object2List,list2Object } from '../../utils/utils';
// import DialogYaml from '../components/DialogYaml.vue';
// import { obj2Yaml } from '../../utils/utils';
import { updateSecretHandler as updateHandler, createSecretHandler as createHandler } from '../../api/secret';
import {useRouter} from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})

const data = reactive({
  clusterId: '',
  namespace: '',
  item: {
    apiVersion: 'v1',
    kind: 'Secret',
    metadata: {
      name: '',
      namespace: '',
      labels: {},
      annotations: {}
    },
    immutable: false,
    stringData: {},
    type: 'Opaque',
    },
  dockerCfg:{
    auths: {},
  },
  options: {
    labelList:[],
    annotationsList:[],
    dataList:[],
    immutableDisabled: false,
    rules: {
      name: [
            {required: true, message: '请输入Secret名称', trigger: 'blur'}
        ],
    },
    secretTypeList:[
      {
        label: '通用类型(默认)',
        value: 'Opaque'
      },
      {
        label: '镜像仓库秘钥',
        value: 'kubernetes.io/dockerconfigjson'
      },
      {
        label: '域名证书',
        value: 'kubernetes.io/tls'
      },
    ],
    secretTypeConfig: {
      'Opaque': [],
      'kubernetes.io/dockerconfigjson':[
        {
          'key': 'address',
          'value': ''
        },
        {
          'key': 'username',
          'value': ''
        },
        {
          'key': 'password',
          'value': ''
        },
        {
          'key': 'email',
          'value': ''
        },
      ],
      'kubernetes.io/tls':[
        {
          'key': 'tls.key',
          'value': ''
        },
        {
          'key': 'tls.crt',
          'value': ''
        }
      ]
    }
  }
})

const secretTypeChanged = (val)=>{
  //把每种类型配置赋值到dataList
  data.options.dataList = data.options.secretTypeConfig[val]
}

const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
let yamlContent = ref('')
let showDetail = ref(false)

const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/secret/list',
        query: {
          clusterId: data.clusterId,
          namespace: data.namespace
        }
      })
    })
    .catch(() => {
      return
    })
}

const submitHandler = (tag) => {
  console.log('tag:', tag)
  console.log('item:', data.item)
  //把list转成object
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationsList)
  const tableData = list2Object(data.options.dataList)
  if(data.item.type == 'kubernetes.io/dockerconfigjson'){
    console.log("创建的是kubernetes.io/dockerconfigjson")
    // user:password
    const user_pass = `${tableData.username}:${tableData.password}`
    const auth = btoa(user_pass.trim())
    const registryConfig = {
      username: tableData.username,
      password: tableData.password,
      email: tableData.email,
      auth: auth
    }
    data.dockerCfg.auths[tableData.address] = registryConfig
    if (data.item.stringData == undefined) {data.item.stringData = {}}
    data.item.stringData['.dockerconfigjson'] = JSON.stringify(data.dockerCfg)
  }else {
    data.item.stringData = tableData
  }

  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: data.item,
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
          // loading.value = false
          // emits('rollback')
        })
  } else {
      // 创建用户，异步的
      updateHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}

const submit = (tag)=> {
    itemRef.value.validate((valid)=>{
        // valid => true
        if(!valid){
        ElMessage({
                    message: "请完善表单内容",
                    type: 'warning',
                })
        }else {
          submitHandler(tag)
        }
    })
}
const namespaceChangeHandler = (clusterId, namespace)=>{
  console.log('namespaceChangeHandler:', clusterId, namespace)
  data.clusterId = clusterId
  data.namespace = namespace
  data.item.metadata.namespace = namespace
}

onBeforeMount(()=>{
  if (props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationsList = object2List(data.item.metadata.annotations)

    //对编辑的数据进行处理
    if (data.item.type == 'kubernetes.io/dockerconfigjson'){
      const dockerCfg = atob(data.item.data['.dockerconfigjson'])
      const dockerCfgObj = JSON.parse(dockerCfg)
      data.dockerCfg = dockerCfgObj
      //取出来配置信息
      const address = Object.keys(dockerCfgObj.auths)[0]
      console.log("address:",address)
      const auth = dockerCfgObj.auths[address]
      const registryConfig = {
        'address': address,
        'username': auth.username,
        'password': auth.password,
        'email': auth.email,
      }
      data.options.dataList = object2List(registryConfig)
      // console.log("dockerconfigjson:",data.item.data['.dockerconfigjson'])
    }else {
      const base64Data = data.item.data
      for (let [key,value] of Object.entries(base64Data)){
        const o ={
          'key': key,
          'value': atob(value)
        }
        //
        data.options.dataList.push(o)
      }
    }
    // data.options.dataList = object2List(data.item.data)
    if (props.method == 'Update' && data.item.immutable){
      data.options.immutableDisabled = true
    }
    delete data.item.data
  }
})  
const {options,item,clusterId,namespace} = toRefs(data)

</script>

<template>
  <CreateOrEditFrame
  :namespace-readonly="props.method == 'Update'"
  :cluster-readonly="props.method == 'Update'"
  @namespace-changed-rollback="namespaceChangeHandler"
  >
  <!-- 头部插入内容 -->

   <template #main>
    <el-form :model="item"
    ref="itemRef">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="基本配置" name="basic" style="height: 240px;">
        <el-row :gutter="5">
          <el-col :span="6">
              <el-form-item  :rules="options.rules.name" label="Secret名称" prop="metadata.name" required>
                  <el-input :disabled="props.method == 'Update'" v-model="item.metadata.name"></el-input>
              </el-form-item>
          </el-col>
          <!-- Secret类型 -->
          <el-col :span="6">
              <el-form-item  label="选择Secret类型" prop="" >
                <el-select 
                v-model="item.type" 
                @change = "secretTypeChanged" 
                placeholder="">
                    <el-option 
                    v-for="item in options.secretTypeList" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
          </el-col>
          <!-- 选择ingressClassName -->
          <el-col :span="6">
              <el-form-item  label="只读" prop="">
                <el-switch :disabled="options.immutableDisabled" v-model="item.immutable"></el-switch>
              </el-form-item>
          </el-col>
        </el-row>

      </el-tab-pane>
      <el-tab-pane 
      label="数据配置" 
      name="rules" 
      >
      <Table 
      :list="options.dataList" 
      value-input-type="textarea"
      :rows="1"
      key-width="320px"
      :readonly="options.immutableDisabled"
      :show-options="item.type=='Opaque'"
      :key-readonly="item.type!='Opaque'"
      ></Table>
      </el-tab-pane>
      <el-tab-pane label="注释及标签" name="labels">
        <el-tabs v-model="labelConfig" tabPosition="left">
            <el-tab-pane label="标签配置" name="labels">
              <Table :list="options.labelList"></Table>
            </el-tab-pane>
            <el-tab-pane label="注释配置" name="annos">
              <Table :list="options.annotationsList"></Table>
            </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>

    <!-- yaml,创建 -->
    <el-form-item class="button-container" style="margin-top: 10px;">
      <el-button @click="submit('yaml')">Yaml</el-button>
      <el-button type="primary" @click="submit()">
        {{ props.method=="Update" ? "更新" : "创建" }}
      </el-button>

     </el-form-item>
    </el-form>
   </template>

  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  :method="props.method"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
</template>

<style scoped>
.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中（如果需要） */
  gap: 10px;               /* 按钮之间的间距 */
}
</style>
